package com.jdk.demo.nio.mReactorThread;

import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Iterator;
import java.util.Set;

import com.jdk.demo.nio.mReactor.MthreadHandler;

public class SubReactor implements Runnable {
	final int index;
	final Selector selector;

	public SubReactor(int index) throws Exception {
		this.index = index;
		// 每个SubReactor 一个selector
		this.selector = SelectorProvider.provider().openSelector();
	}

	/**
	 * 注册chanel
	 *
	 * @param c
	 * @throws Exception
	 */
	public void registerChannel(SocketChannel c) throws Exception {
		c.configureBlocking(false);
		System.out.println(c.getRemoteAddress() + " registered in " + index + ", thread: " + Thread.currentThread().getName());
		//将Handler作为callback对象
		new MthreadHandler(selector, c);
	}

	@Override
	public void run() {
		while (true) {
			try {
				// 每个SubReactor 自己做事件分派处理读写事件
				selector.select(5000);
				Set<SelectionKey> keys = selector.selectedKeys();
				Iterator<SelectionKey> it = keys.iterator();
				SelectionKey key = null;
				while (it.hasNext()) {
					key = (it.next());
                    it.remove();
                    dispatch(key);
				}

			} catch (Exception e) {

			}
		}
	}

	void dispatch(SelectionKey k) {
        Runnable r = (Runnable) (k.attachment());
        //调用之前注册的callback对象
        if (r != null) {
            r.run();
        }
    }

}